/**
 * Created by vimer on 15/8/25.
 */

var updateSerialList = function(){
    // 初始化串口列表
    Serial.getList(function(arr){
        Ui.initSerial(arr );
    });
}




$(document).ready(function(){
    Ui.initLog();
    Log.setLogger(Ui.appendLog);

    updateSerialList();
    var path = KeyValue.get("firmware_path");
    if(path){
        $("#firmware-path").val(path) ;
    }

    $("#start-firmware").click(function(e){
        e.preventDefault();
        var _this = $(this);
        if(_this.hasClass("disabled")){
            return;
        }
        var path = $("#firmware-path").val();
        var fs = require("fs");
        if(!path){
            Ui.updateMainLog(true,"请先选择固件文件");
            return;
        }
        fs.exists(path,function(result){
            if(!result){
                Ui.updateMainLog(true,"固件文件不存在，请选择正确的文件");
                return ;
            }
            Ui.updateMainLog("开始烧写固件");
            _this.addClass('disabled');
            var hasError = false;
            startFirmware(path,function(data){
                    Log.serialLog(data);
                },
                function(data){
                    _this.removeClass('disabled');
                    Log.serialLog(data);
                    Ui.updateMainLog(true,"烧写出现错误");
                    hasError = true;
                },
                function(){
                    _this.removeClass('disabled');
                    if(!hasError){
                        Ui.updateMainLog("烧写完成");
                    }
                });
        });
    });

    $("#firmware-path").change(function(){
        var _this = $(this);
        var val =  _this.val();
        var fs = require("fs");
        if (val ){
            fs.exists(val,function(result){
                if(result) {
                    KeyValue.set("firmware_path" ,val);
                }

            });
        }
    });


});

